package dmwr.util;

import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Random;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Passwords {

	private static final Random RANDOM = new SecureRandom();
	private static final int ITERATIONS = 10000;
	private static final int KEY_LENGTH = 256;

	public static byte[] hash(char[] password, byte[] salt) {
		KeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
		try {
			return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
					.generateSecret(spec).getEncoded();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static boolean check(char[] password, byte[] salt, byte[] expected) {
		byte[] hash = hash(password, salt);
		if (hash.length != expected.length)
			return false;
		for (int i = 0; i < hash.length; i++) {
			if (hash[i] != expected[i]) {
				return false;
			}
		}
		return true;
	}

	public static byte[] salt() {
		byte[] salt = new byte[16];
		RANDOM.nextBytes(salt);
		return salt;
	}
}
